package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.DateUtils;
import org.footballmanager.pandafootball.common.util.MD5Encoder;
import org.footballmanager.pandafootball.system.dao.FootUserDao;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.domain.enums.QX;
import org.footballmanager.pandafootball.system.form.impl.FootUserSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FootUserServiceImpl extends ServiceImpl<FootUser> implements FootUserService {
	@Autowired
	private FootUserDao footUserDao;
	@Autowired
	private FootTeamService footTeamService;
	@Autowired
	private FootClubService footClubService;
	@Autowired
	private FootZnxService footZnxService;
	@Autowired
	private FootScinfoService footScinfoService;
	@Autowired
	private FootYysService footYysService;
	@Autowired
	private FootChipService footChipService;
	@Autowired
	private FootRankService footRankService;
	@Autowired
	private FootLotteryService footLotteryService;
	@Autowired
	private FootUserPersonService footUserPersonService;
	@Autowired
	private FootSjService footSjService;
	@Autowired
	private FootQdService footQdService;
	@Autowired
	private FootTtService footTtService;
    @Autowired
    private FootSociatyInfoService footSociatyInfoService;

    /**
     * 更新用户信息
     * @param entity 实体类
     * @param request 请求
     * @return 成功或失败
     */
    @Override
    @Transactional
    @SystemServiceLog(description = "更新用户信息")
    public int updateNotNull(FootUser entity, HttpServletRequest request){
        entity.setPassword(MD5Encoder.strToMD5(entity.getPassword()));
        return super.updateNotNull(entity, request);
    }

	@Override
	@Transactional
	public int delete(Serializable id, HttpServletRequest request) {
		FootUser t = this.get(id);
		if(Constants.ADMIN.equals(t.getName())){
			return 0;
		}
		deleteYys(t, request);
		deleteZnx(t, request);
		if(t.getJoins()){
			deleteScinfo(t, request);
			deleteQd(t, request);
			deleteClub(t, request);
			deleteRank(t, request);
			deleteTt(t, request);
			deleteSociaty(t, request);
			//下放该用户的所有球员
			footUserPersonService.deleteAllPerson(t.getId(), request);
		}
		log.info("删除用户:" + t.toString());
		return super.delete(id, request);
	}

    private void deleteSociaty(FootUser t, HttpServletRequest request) {
        //删除Sociaty信息
        footSociatyInfoService.deleteByUserid(t.getId(), request);
    }

    private void deleteTt(FootUser t, HttpServletRequest request) {
		//删除Tt信息
		List<FootTt> ttList = footTtService.getTtsByUserid(t.getId());
		if(ttList != null && !ttList.isEmpty()){
			for(FootTt tt: ttList){
				footTtService.delete(footTtService.get(tt.getId()), request);
			}
		}
	}

	private void deleteRank(FootUser t, HttpServletRequest request) {
		//删除rank信息
		List<FootRank> rankList = footRankService.getRanksByUserid(t.getId());
		if(rankList != null && !rankList.isEmpty()){
			for(FootRank fr: rankList){
				footRankService.delete(footRankService.get(fr.getId()), request);
			}
		}
	}

	private void deleteClub(FootUser t, HttpServletRequest request) {
		//删除俱乐部
		List<FootClub> clubList = footClubService.getClubsByUseridandSj(t.getId(), footSjService.getSj());
		if(clubList != null && !clubList.isEmpty()){
			for(FootClub fc: clubList){
				footClubService.delete(footClubService.get(fc.getId()), request);
			}
		}
	}

	private void deleteQd(FootUser t, HttpServletRequest request) {
		//删除球队
		FootTeam team = footTeamService.getTeamByUserid(t.getId());
		if(team != null){
			footTeamService.delete(team.getId(), request);
		}
	}

	private void deleteScinfo(FootUser t, HttpServletRequest request) {
		//删除收藏
		List<FootScinfo> scList = footScinfoService.findCollectionByUserId(t.getId());
		if(scList != null && !scList.isEmpty()){
			for(FootScinfo fs: scList){
				footScinfoService.delete(fs.getId(), request);
			}
		}
	}

	private void deleteZnx(FootUser t, HttpServletRequest request) {
		//删除收件箱
		List<FootZnx> znxList = footZnxService.findZnxsByUserId(t.getId());
		if(znxList != null && !znxList.isEmpty()){
			for(FootZnx fz: znxList){
				footZnxService.delete(fz.getId(), request);
			}
		}
	}

	private void deleteYys(FootUser t, HttpServletRequest request){
		//友谊赛
		FootYys yys = footYysService.findYysByUserId(t.getId());
		if(yys != null){
			footYysService.delete(yys.getId(), request);
		}
	}

	@Override
	public List<FootUser> getAllWithoutAdmin(HttpServletRequest request){
	    Example example = new Example(FootUser.class);
	    Example.Criteria criteria = example.createCriteria();
	    criteria.andNotEqualTo("name", Constants.ADMIN);
        if(request != null){
            FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
            criteria.andNotEqualTo("name", user.getName());
        }
	    return this.findall(example);
	}

	@Override
	@Transactional
	public int save(FootUser u, HttpServletRequest request) {
		u.setPassword(MD5Encoder.strToMD5(u.getPassword()));
		u.setCreateId((Long)request.getSession().getAttribute(Constants.USERID));
		u.setCreateTime(new Date());
		u.setUpdateId((Long)request.getSession().getAttribute(Constants.USERID));
		u.setUpdateTime(new Date());
		footUserDao .insert(u);
		
		if(u.getQdId() != null){
			FootQd qd = footQdService.get(u.getQdId());
			if(qd != null){
				//添加俱乐部信息
				footClubService.saveNewClub(u, request);
				//添加队伍信息
				footTeamService.saveNewTeam(u, qd.getId(), request);
				//添加排位赛信息
				footRankService.saveNewRank(u, qd.getId(), request);
				//添加天梯赛信息
				footTtService.saveNewTt(u, qd.getId(), request);
                //添加战队初始值
                footSociatyInfoService.saveNewSociaty(u, request);
			}
		}
		return saveNewUser(u, request);
	}

	@Override
	public int saveNewUser(FootUser u, HttpServletRequest request){
	    u.setSd(false);
		//分别给注册用户和管理员发送收件箱,提醒
		if(u.getJoins()){
			u.setQx(QX.MEMBER);
			//添加碎片时间信息
			footLotteryService.saveNewLottery(u, request);
			//添加碎片信息
			footChipService.saveNewChip(u, request);
		}else{
			u.setQx(QX.NORMAL);
			footZnxService.sendZnx(u.getId(), this.getAdminUserid(), "有新注册一般用户", null, null, request);
		}
		//添加热身赛信息
		footYysService.saveNewYys(u, request);
		//随机分配11个球员
		footUserPersonService.randomLow75(u.getId(), request);
		return this.updateNotNull(u, request);
	}
	
	/**
	 * 获取管理员账号信息
	 */
	@Override
	public Long getAdminUserid(){
		Example example = new Example(FootUser.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", Constants.ADMIN);
		FootUser user = this.findByExample(example);
		if(user != null){
			return user.getId();
		}
		return null;
	}
	
	/**
	 * 判断一般用户是否超过三个月未登陆,如果未登陆删除账号
	 */
	@Scheduled(cron="0 0 0 * * ?") //每天0点触发
	@Transactional
	public void processUserNoLogin() {
		Date date = new Date();
		List<FootUser> list = this.getall();
		if(list != null && !list.isEmpty()){
			for(FootUser fu: list){
				if(!fu.getJoins() && (date.getTime() - fu.getZhdlsj().getTime() > 7776000000L)){
					this.delete(fu.getId(), null);
				}
			}
		}
	}

	@Override
	@Transactional
	public void cancelLogin(boolean issd, HttpServletRequest request) {
		List<FootUser> userList = this.getall();
		if(userList != null && !userList.isEmpty()){
			for(FootUser user: userList){
				user.setSd(issd);
				this.updateNotNull(user, request);
			}
		}
	}

	@Override
	public List<FootUser> findGameIdIsNotNull() {
		Example example = new Example(FootUser.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIsNotNull("gameId");
		criteria.andNotEqualTo("name", "admin");
		return this.findall(example);
	}

	@Override
	public FootUser findUserByName(String name) {
		Example example = new Example(FootUser.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", name);
		return this.findByExample(example);
	}

	@Override
	public List<FootUser> findUsersByNike(String nike) {
		Example example = new Example(FootUser.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("nike", nike);
		return this.findall(example);
	}

	@Override
	public FootUser findUserByNameEmail(String name, String email) {
		Example example = new Example(FootUser.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", name);
		criteria.andEqualTo("email", email);
		return this.findByExample(example);
	}

	@Override
	@Transactional
	public void changeUser2Vip(FootUser user, HttpServletRequest request) {
        FootUser fuser = footUserDao.selectByPrimaryKey(user.getId());
        fuser.setQx(user.getQx());
        fuser.setVip(DateUtils.getNextMonthDate(new Date()));
		switch (fuser.getQx().getValue()) {
		case 3:
			processVip1(fuser, request);
			break;
		case 4:
			processVip2(fuser, request);
			break;
		case 5:
			processVip3(fuser, request);
			break;
		default:
			user.setQx(QX.MEMBER);
			break;
		}
		this.updateNotNull(fuser, request);
	}

	private void processVip1(FootUser user, HttpServletRequest request){
		if(user.getFirst()){
			footChipService.randomGetChip(user.getId(), 3, 5, request);
			user.setFirst(false);
		}
		footChipService.randomGetChip(user.getId(), 2, 5, request);
		footChipService.randomGetChip(user.getId(), 3, 5, request);
		user.setQx(QX.VIPONE);
	}

	private void processVip2(FootUser user, HttpServletRequest request){
		if(user.getFirst()){
			footChipService.randomGetChip(user.getId(), 3, 5, request);
			footChipService.randomGetChip(user.getId(), 4, 2, request);
			user.setFirst(false);
		}
		footChipService.randomGetChip(user.getId(), 3, 5, request);
		footChipService.randomGetChip(user.getId(), 4, 2, request);
		user.setQx(QX.VIPTWO);
	}

	private void processVip3(FootUser user, HttpServletRequest request){
		if(user.getFirst()){
			footChipService.randomGetChip(user.getId(), 4, 5, request);
			footChipService.randomGetChip(user.getId(), 5, 1, request);
			user.setFirst(false);
		}
		footChipService.randomGetChip(user.getId(), 4, 5, request);
		footChipService.randomGetChip(user.getId(), 5, 1, request);
		user.setQx(QX.VIPTHREE);
	}

	@Override
	public double getVipLevel(FootUser user, HttpServletRequest request) {
		double result = 1D;
		Date date = new Date();
		if(null != user && user.getVip() != null){
			if(user.getVip().getTime() < date.getTime()){
				user.setQx(QX.MEMBER);
				this.updateNotNull(user, request);
			}
			if(user.getQx().equals(QX.VIPONE)){
				result = 1.1D;
			}else if(user.getQx().equals(QX.VIPTWO)){
				result = 1.2D;
			}else if(user.getQx().equals(QX.VIPTHREE)){
				result = 1.3D;
			}
		}
		return result;
	}

    /**
     * 查询
     *
     * @param entityname         实体类名
     * @param map                参数
     * @param footUserSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootUserSearchForm footUserSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footUserSearchForm);
        Page<FootUser> page = PageHelper.startPage(footUserSearchForm.getPageIndex(), footUserSearchForm.getPageSize());
        List<FootUser> list = this.findall(footUserSearchForm.buildSearchCommond());
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param footUserSearchForm 条件
     * @param request            请求
     */
    @Override
    public void deleteAll(FootUserSearchForm footUserSearchForm, HttpServletRequest request) {
        if(footUserSearchForm.getSelectIds() != null){
            String[] result = footUserSearchForm.getSelectIds().split(Constants.COMMA);
            for(String id: result){
                this .delete(Long.parseLong(id), request);
            }
        }
    }
}
